<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue Listener</title>
</head>
<body>
    <div id="watch-example">
        <p>
            Ask a yes/no question:
            <input v-model="question">
        </p>
        <p>{{ answer }}</p>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
    <script>
        var watchExampleVM = new Vue({
            el: "#watch-example",
            data: {
                question: "",
                answer: "I can't give you an answer until you ask a question!"
            },
            watch: {
                // 如果question发生改变，这个函数就会运行
                question: function(newQuestion, oldQuestion) {
                    this.answer = "Waiting for you to stop typing..."
                    this.debounceGetAnswer()
                }
            },
            created: function() {
                this.debounceGetAnswer = _.debounce(this.getAnswer, 500)
            },
            methods: {
                getAnswer: function() {
                    if (this.question.indexOf('?') === -1) {
                        this.answer = "Questions usually contain a question mark.;->"
                        return
                    }
                    this.answer = "Thinking..."
                    var vm = this
                    axios.get('https://yesno.wtf/api')
                        .then(function (response) {
                            vm.answer = _.capitalize(response.data.answer)
                        })
                        .catch(function (error) {
                            vm.answer = "Error! Could not reach the API," + error
                        })
                }
            }
        })
    </script>
</body>
</html>